package com.study.httpserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;

import javax.net.ssl.SSLException;
import java.security.cert.CertificateException;

/**
 * HTTP服务器
 */
public class httpServer {
    private static final int PORT = 9000;
    private static EventLoopGroup group = new NioEventLoopGroup();
    private static ServerBootstrap b = new ServerBootstrap();
    // 是否启用HTTPS 启用则需要访问 https://localhost:9000/ ，否则 http://localhost:9000/
    private static final boolean SSL = true;

    public static void main(String[] args) throws InterruptedException, CertificateException, SSLException {
        final SslContext sslContext;
        if (SSL) {
            // Netty提供的ssl加密，缺省值
            SelfSignedCertificate ssc = new SelfSignedCertificate();
            sslContext = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
        } else
            sslContext = null;
        try {
            b.group(group)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ServerHandlerInit(sslContext));
            ChannelFuture future = b.bind(PORT).sync();
            // 监听服务器关闭
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully().sync();
        }
    }
}
